package org.ztest.douban;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

import org.ztest.http.HttpUtil;

public class DoubanMeizi
{
	private ExecutorService es;
	
	private String host;
	private String directory;
	private AtomicInteger ai;
	
	private Consumer<String> consumer = arg -> parseLine(arg);
	
	public DoubanMeizi()
	{
		host = "http://www.doubanmeizi.com/page/%d";
		directory = "E:\\Douban\\";
		es = Executors.newFixedThreadPool(8);
		ai = new AtomicInteger(1);
	}
	
	public void startDownload()
	{
		int i = 0;
		while (i++ < 54)
		{
			String url = String.format(host, i);
			es.submit(() -> {
    			try {
    				HttpUtil.GET(url, consumer);
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
			});
		}
	}
	
	public void parseLine(String line)
	{
		line = line.trim();
		if (!line.startsWith("<img") && !line.startsWith("<p><img"))
		{
			return;
		}
		
		int startIdx = line.indexOf("src=\"");
		String subLine = line.substring(startIdx + 5);
		int endIdx = subLine.indexOf("\"");
		String imgUrl = subLine.substring(0, endIdx);
	
		es.submit(() -> downloadImage(imgUrl, getSavePath()));
	}
	
	public void downloadImage(String imgUrl, Path savePath)
	{
		try
		{
			byte[] imgData = HttpUtil.GET1(imgUrl);
			Files.write(savePath, imgData);
		}
		catch (NullPointerException | IOException e)
		{
			e.printStackTrace();
		}
	}
	
	public Path getSavePath()
	{
		String filePath = directory + ai.getAndIncrement() + ".jpg";
		return Paths.get(filePath);
	}
}
